#include "transcoder_core.h"

sem_t get_core_id_mutex;
int num_cores;
int ID_OF_THE_FIRST_CORE_TO_BIND;
int NEXT_BINDING_CORE_ID = 0;

int get_core_id()
{
	sem_wait(&get_core_id_mutex);
	int id = NEXT_BINDING_CORE_ID;
	NEXT_BINDING_CORE_ID += 1;
	sem_post(&get_core_id_mutex);
	return id % num_cores;
}

void binding_core()
{
	int core_id = get_core_id();
	cpu_set_t mask;
	CPU_ZERO(&mask);
	CPU_SET(core_id, &mask);
	if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
		fprintf(stdout, "Error 23: core id = %d, thread set affinity failed\n", core_id);
	}
}

void core_binding_initialize()
{
	sem_init(&get_core_id_mutex, 0, 1);
	num_cores = sysconf(_SC_NPROCESSORS_CONF);
	NEXT_BINDING_CORE_ID = ID_OF_THE_FIRST_CORE_TO_BIND;
}
